<template>
  <div class="search-input">
    <span class="iconfont icon-header-search"></span>
    <input class="input" type="text" placeholder="景点/美食/酒店/按摩/KTV"
      v-model="searchValue"
      @input="onInputValue"
    >
    <span v-if="searchValue" class="remove" @click="() => searchValue=''">x</span>
  </div>
</template>

<script>
import {SearchModel} from '@/models/search.js'
import { mapState } from 'vuex';
import tools from '@/utils/tools.js'

export default {
  name: 'SearchInput',
  data() {
    return {
      searchValue: '',
    }
  },
  methods: {
    async getSearchDatas (keyword, cityId) {
      const searchModel = new SearchModel();
      const res = await searchModel.getSearchData(keyword, cityId)
      
      if(res && res.status !== -1) {
        // 数据获取成功
        this.$emit('searchData', res.data);
        console.log(res.data);
      } else {
        this.$emit('searchData', res);
      }
    },
    onInputValue: tools._throttle(function() {
       const keyword = this.searchValue.replace(/\s+/g, '');
        // console.log(keyword);

        //输入的内容为空
        if(keyword.length <= 0) {
          this.$emit('searchData', {
          });
          return;
        }
        
        this.getSearchDatas(keyword, this.cityId)
    }) 
  },
  computed: {
    ...mapState(['cityId'])
  }
}
</script>

<style lang="scss" scoped>
.search-input {
  position: relative;
  box-sizing: border-box;
  width: 100%;
  height: .5rem;
  padding: .1rem;
  background-color: #fff;
  .iconfont {
    position: absolute;
    left: .18rem;
    top: .20rem;
  }
  .input {
    width: 100%;
    height: 100%;
    border: 1px solid #aaa;
    border-radius: .1rem;
    font-size: .14rem;
    text-indent: 2em;
    color: #333;
  }
  .remove {
    display: inline-block;
    position: absolute;
    right: .18rem;
    top: .18rem;
    width: .2rem;
    height: .2rem;
    text-align: center;
    line-height: .2rem;
    font-size: .14rem;
    color: #aaa;
  }
}
</style>